package ru.spbsu.electromenu.storage.db;

import org.springframework.jdbc.core.RowMapper;
import ru.spbsu.electromenu.model.Alert;
import ru.spbsu.electromenu.storage.AlertStorage;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Date: 3/22/11
 * Time: 1:04 AM
 *
 * @author Artem Titov
 */
public class AlertDbStorage extends AbstractDbStorage implements AlertStorage {

    private final RowMapper<Alert> ALERT_ROW_MAPPER = new RowMapper<Alert>() {
        @Override
        public Alert mapRow(ResultSet rs, int i) throws SQLException {
            final Alert alert = new Alert();
            alert.setId(rs.getInt("Id"));
            alert.setAlertMessage(rs.getString("AlertMessage"));
            alert.setTime(rs.getDate("Time"));
            alert.setSessionId(rs.getInt("SessionId"));
            alert.setActive(rs.getBoolean("Active"));
            return alert;
        }
    };

    @Override
    public Alert get(int id) {
        return jdbcTemplate.queryForObject("select * from `Alert` where `Id`=?", ALERT_ROW_MAPPER, id);
    }

    @Override
    public int put(Alert alert) {
        return jdbcTemplate.update("insert into `Alert`(`SessionId`, `AlertMessage`, `Time`, `Active`) values (?, ?, ?, ?)",
                alert.getSessionId(),
                alert.getAlertMessage(),
                alert.getTime(),
                true);
    }

    @Override
    public int update(Alert alert) {
        return jdbcTemplate.update("update `Alert` set `SessionId`=?, `AlertMessage`=?, `Time`=?, `Active`=? where `Id`=?",
                alert.getSessionId(),
                alert.getAlertMessage(),
                alert.getTime(),
                alert.isActive(),
                alert.getId());
    }

    @Override
    public int delete(int id) {
        return jdbcTemplate.update("delete from `Alert` where `Id`=?", id);
    }

    @Override
    public List<Alert> getALl() {
        return jdbcTemplate.query("select * from `Alert`", ALERT_ROW_MAPPER);
    }
}
